import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Modal, message } from 'antd'; // 添加 Modal 和 message
import { useGlobalContext } from '../../context/GlobalContext';
import IconAvatar from '../../assets/avatar.png';
import './index.css';
import { getApiUrl } from '../../config/api';

export const SettingsPage = () => {
  const navigate = useNavigate();
  const { user, logout, updateUserInfo } = useGlobalContext();
  const [nickname, setNickname] = useState(user?.nickname || '未设置');
  
  const [phone, setPhone] = useState(user?.phone || '');
  const [avatar, setAvatar] = useState(user?.avatar || IconAvatar);
  const [isPhoneModalVisible, setIsPhoneModalVisible] = useState(false);
  const [phoneInput, setPhoneInput] = useState(user?.phone || '');

  // 手机号格式验证
  const validatePhone = (phone) => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };

  // 处理手机号绑定
  const handlePhoneSubmit = async () => {
    if (!validatePhone(phoneInput)) {
      message.error('请输入正确的手机号格式');
      return;
    }

    try {
      const token = localStorage.getItem('token');
      const cleanToken = typeof token === 'string' ? token.replace(/['"]+/g, '') : token;

      const response = await fetch(getApiUrl('/api/user/profile'), {  // 修改为 profile 接口
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cleanToken}`,
        },
        body: JSON.stringify({ phone: phoneInput })
      });

      const data = await response.json();

      if (data.ok) {
        setPhone(phoneInput);
        // 更新全局状态
        const updatedUser = { ...user, phone: phoneInput };
        updateUserInfo(updatedUser);
        // 更新本地存储
        localStorage.setItem('user', JSON.stringify(updatedUser));
        message.success('手机号绑定成功');
        setIsPhoneModalVisible(false);
      } else {
        throw new Error(data.error || '绑定失败');
      }
    } catch (error) {
      console.error('绑定手机号失败:', error);
      message.error(error.message || '绑定手机号失败，请稍后重试');
    }
  };

  const handleBack = () => {
    navigate('/chat');
  };

  const handleFeedback = () => {
    navigate('/feedback');
  };
  
  const handleAbout = () => {
    navigate('/about');
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const handleAvatarChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      alert('请上传图片文件');
      return;
    }

    // 验证文件大小（限制为 2MB）
    if (file.size > 2 * 1024 * 1024) {
      alert('图片大小不能超过 2MB');
      return;
    }

    try {
      const formData = new FormData();
      formData.append('avatar', file);
  
      const token = localStorage.getItem('token');
      // 移除 JSON.parse，直接使用 token
      const cleanToken = typeof token === 'string' ? token.replace(/['"]+/g, '') : token;
  
      const response = await fetch(getApiUrl('/api/user/avatar'), {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
        },
        body: formData
      });
  
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '上传失败');
      }

      const data = await response.json();
      
      if (data.ok) {
        setAvatar(data.avatarUrl);
        // 更新全局用户信息
        updateUserInfo({ ...user, avatar: data.avatarUrl });
      } else {
        throw new Error(data.error || '上传失败');
      }
    } catch (error) {
      console.error('上传头像失败:', error);
      alert(error.message || '上传头像失败，请稍后重试');
    }
  };

  return (
    <div className="settings-page">
      <div className="settings-header">
        <div className="back-button" onClick={handleBack}>
          <span className="back-arrow">‹</span>
          <span>返回</span>
        </div>
        <h1>设置</h1>
      </div>
      
      <div className="settings-content">
        <div className="settings-section">
          <div className="settings-item avatar-setting">
            <span>头像</span>
            <div className="avatar-wrapper">
              <img src={avatar} alt="用户头像" />
              <input 
                type="file" 
                accept="image/*"
                onChange={handleAvatarChange}
                id="avatar-upload"
              />
              <label htmlFor="avatar-upload">更换头像</label>
            </div>
          </div>

          <div className="settings-item">
            <span>昵称</span>
            <input 
              type="text"
              value={nickname}
              onChange={(e) => setNickname(e.target.value)}
              placeholder="设置昵称"
            />
          </div>

          <div className="settings-item">
            <span>手机号</span>
            <div className="phone-input" onClick={() => setIsPhoneModalVisible(true)}>
              {phone || '绑定手机号'}
            </div>
          </div>
        </div>

        {/* 添加手机号绑定弹窗 */}
        <Modal
          title="绑定手机号"
          open={isPhoneModalVisible}
          onOk={handlePhoneSubmit}
          onCancel={() => setIsPhoneModalVisible(false)}
          cancelText="取消"
          okText="确定"
        >
          <input
            type="tel"
            value={phoneInput}
            onChange={(e) => setPhoneInput(e.target.value)}
            placeholder="请输入手机号"
            className="phone-modal-input"
          />
        </Modal>

        <div className="settings-section">
          <div className="settings-item link-item" onClick={handleFeedback}>
            <span>帮助与反馈</span>
            <i className="arrow-right">›</i>
          </div>
          
          <div className="settings-item link-item" onClick={handleAbout}>
            <span>关于 AI Cube</span>
            <i className="arrow-right">›</i>
          </div>
        </div>

        <div className="settings-section">
          <button className="logout-button" onClick={handleLogout}>
            退出登录
          </button>
        </div>
      </div>
    </div>
  );
};